﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RedSand.Web.Mvc;
using RedSand.Site.Models;

namespace RedSand.Site.Controllers
{
    public class PostController : BaseController
    {
        public ActionResult Manager()
        {
            return View(new ManagerModel { Title = "News manager", AttachTinyMce = true });
        }
        public ActionResult Index()
        {
            return View();
        }

        [AjaxOrChildAction]
        public ActionResult feList(int? page, string keyword, int? userId, string procedure = "NewsGetList")
        {
            int TotalRecord = 0;
            var ListNew = RsDataManager.GetList<NewsFullInfo>(procedure, new { Keyword = keyword, userId = userId, status = 1 }, page ?? 1, 5, ref TotalRecord);
            ViewBag.TotalRecord = TotalRecord;
            ViewBag.RouteValues = new { Keyword = keyword, userId = userId };
            return PartialView(ListNew);
        }
        [HttpGet]
        public ActionResult feListByCategory(string AliasParent, string AliasChild, int? page)
        {
            int TotalRecord = 0;
            var ListNew = RsDataManager.GetList<NewsFullInfo>("NewsGetList", new { AliasParent = AliasParent, AliasChild = AliasChild, status = 1 }, page ?? 1, 5, ref TotalRecord);
            ViewBag.TotalRecord = TotalRecord;
            ViewBag.RouteValues = new { AliasParent = AliasParent, AliasChild = AliasChild };
            ViewBag.AliasParent = AliasParent;
            ViewBag.AliasChild = AliasChild;
            return View(ListNew);
        }
        [HttpGet]
        public ActionResult feDetails(string AliasNews)
        {
            AliasNews = AliasNews.Replace(".html", "");
            ViewBag.Title = AliasNews;
            var info = RsDataManager.GetInfo<NewsFullInfo>("NewsGetInfo", "Alias", AliasNews);
            RsDataManager.ExecuteGetReturn("NewsAddTotalView", new { NewsID = info.NewsID });
            return View(info);
        }
        [HttpGet]
        [Authorize]
        public ActionResult feCreate()
        {
            ViewBag.SelectListCategory = GetListCategory();
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult feCreate(NewsInfo info)
        {
            if (ModelState.IsValid)
            {
                if (RsDataManager.GetInfo<NewsFullInfo>("NewsGetInfo", "Alias", info.Alias) != null)
                    AddMessage("Alias is exist");
                if (string.IsNullOrWhiteSpace(info.Content))
                    AddMessage("Content is Empty");
                if (!MvcHtmlString.IsNullOrEmpty(GetMessage(false)))
                {
                    ModelState.Clear();
                    info.Content = HtmlDecode(info.Content);
                    ViewBag.SelectListCategory = GetListCategory();
                    return View(info);
                }
                if (!string.IsNullOrWhiteSpace(info.Image)) info.Image = SaveImage(null);
                info.Content = HtmlDecode(info.Content);
                info.CreateDate = DateTime.Now;
                info.Status = 1;
                info.TotalView = 0;
                info.TotalDownload = 0;
                info.UserID = UserID;
                if (RsDataManager.Save("NewsSave", info) > 0)
                {
                    AddMessage(Message.CreateSuccess);
                    return Redirect(feGenerateTitleHref(info.Alias, info.CategoryID.Value));
                }
                else
                {
                    AddMessage(Message.CreateError);
                }
            }
            ModelState.Clear();
            AddMessage("Some invalid data"); 
            return View(info);
        }

        [HttpGet]
        [Authorize]
        public ActionResult feEdit(string AliasNews)
        {
            AliasNews = AliasNews.Replace(".html", "");
            var info = RsDataManager.GetInfo<NewsFullInfo>("NewsGetInfo", "Alias", AliasNews);
           
            if (info.UserID == UserID || IsAdministrator || IsContentManager)
            {
                ViewBag.SelectListCategory = GetListCategory();
                ViewBag.Title = AliasNews;
                return View(info);
            }
            else
            {
                AddMessage(Message.AccessDenied);
            }
            if (Request.UrlReferrer != null)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
            var link = feGenerateTitleHref(info.Alias, info.CategoryID.Value);
            return Redirect(link.Remove(link.LastIndexOf("/")));
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult feEdit(NewsInfo info)
        {
            if (ModelState.IsValid)
            {
                ModelState.Clear();
                var oldinfo = RsDataManager.GetInfo<NewsFullInfo>("NewsGetInfo", "Alias", info.Alias);
                if (oldinfo != null && oldinfo.NewsID != info.NewsID)
                    AddMessage("Alias is exist");

                if (string.IsNullOrWhiteSpace(info.Content))
                    AddMessage("Content is Empty");

                if (!MvcHtmlString.IsNullOrEmpty(GetMessage(false)))
                {
                    
                    ViewBag.msgError = HttpUtility.HtmlDecode(ViewBag.msgError);
                    ViewBag.SelectListCategory = GetListCategory();
                    info.Content = HtmlDecode(info.Content);
                    return View(info);
                }

                oldinfo = oldinfo ?? RsDataManager.GetInfo<NewsFullInfo>("NewsGetInfo", "NewsID", info.NewsID);
                info.CreateDate = oldinfo.CreateDate;
                info.Status = oldinfo.Status;
                info.TotalView = oldinfo.TotalView;
                info.UserID = oldinfo.UserID;

                info.Image = string.IsNullOrWhiteSpace(info.Image) ? oldinfo.Image : SaveImage(oldinfo.Image);


                info.Content = HtmlDecode(info.Content);
                if (RsDataManager.Save("NewsSave", info) > 0)
                {
                    AddMessage(Message.UpdateSuccess);
                    return Redirect(feGenerateTitleHref(info.Alias, info.CategoryID.Value));
                }
                else
                {
                    AddMessage("System error, please try again");
                    return View(info);
                }
            }
            ModelState.Clear();
            AddMessage("Some invalid data");
            return View(info);
        }
        [Authorize]
        public ActionResult feDetele(string AliasNews, int delete = 0)
        {
            AliasNews = AliasNews.ToLower();
            var info = RsDataManager.GetInfo<NewsInfo>("NewsGetInfo", "Alias", AliasNews.Replace(".html", ""));
            if (info.UserID == UserID || IsAdministrator || IsContentManager)
            {
                if (RsDataManager.Delete("NewsDelete", new { NewsID = info.NewsID, delete = delete }))
                {
                    if (delete == 1) DeleteFile(info.Image);
                    AddMessage(Message.DeleteSuccess);
                }
                else
                {
                    AddMessage(Message.DeleteError);
                }
            }
            else
            {
                AddMessage(Message.AccessDenied);
            }
            if (Request.UrlReferrer != null)
            {
                return Redirect(Request.UrlReferrer.ToString().ToLower().Replace(AliasNews, ""));
            }
            return Redirect(feGenerateTitleHref(info.Alias, info.CategoryID.Value).Replace(AliasNews, ""));
        }                                                                   

        [AjaxOrChildAction]
        public MvcHtmlString feGenerateActionLink(string alias, string action, int userId)
        {
            string link = "/" + action.ToLower() + "/" + alias.ToLower() + ".html";
            string patern = getActionLinkPatern(link);
            if (RsDataManager.ExecuteGetReturn("UserAuthenticate", new { Username = User.Identity.Name, Link = patern }) > 0)
            {
                if (userId == UserID || IsAdministrator || IsContentManager)
                {
                    return MvcHtmlString.Create("<a title='" + action.ToLower() + "' href='" + link + "' class='" + action.ToLower() + "-post'></a>");
                }
            }
            return MvcHtmlString.Empty;
        }
        [AjaxOrChildAction]
        public MvcHtmlString feGenerateTitleLink(string alias, string title, int category)
        {
            return MvcHtmlString.Create("<a href='" + feGenerateTitleHref(alias, category) + "'>" + title + "</a>");
        }
        private string feGenerateTitleHref(string alias, int category)
        {
            var info = RedSand.Web.Mvc.RsDataManager.GetInfo<RedSand.Site.Models.CategoryInfo>("CategoryGetInfo", new { CategoryID = category });
            var link = info.Alias.ToLower();
            if (info.ParentID.HasValue && info.ParentID > 0)
            {
                var parent = RedSand.Web.Mvc.RsDataManager.GetInfo<RedSand.Site.Models.CategoryInfo>("CategoryGetInfo", new { CategoryID = info.ParentID });
                link = parent.Alias.ToLower() + "/" + link;
            }
            return "/" + link + "/" + alias.ToLower() + ".html";
        }

        public List<SelectListItem> GetListCategory()
        {
            List<SelectListItem> Sll = new List<SelectListItem>();
            var Lts = RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = 0 });
            if (Lts != null)
                foreach (var items in Lts)
                {
                    Sll.Add(new SelectListItem { Text = items.Alias, Value = items.CategoryID.ToString() });
                    var LtsChild = RsDataManager.GetList<CategoryInfo>("CategoryGetList", new { ParentID = items.CategoryID });
                    if (LtsChild != null)
                        foreach (var itemschild in LtsChild)
                        {
                            Sll.Add(new SelectListItem { Text = items.Alias + " --- " + itemschild.Alias, Value = itemschild.CategoryID.ToString() });
                        }
                }
            return Sll;
        }
    }
}
